<?php
/**
 * Created by PhpStorm.
 * User: yangfan
 * Date: 2020/1/17
 * Time: 3:58 PM
 */

namespace App\BO\Wechat;

use App\BO\Wechat\Meta\WechatPayResultMeta;
use App\BO\Wechat\Meta\WechatRefundMeta;
use App\BO\Wechat\Meta\WechatRefundResultMeta;
use App\Entities\PaymentEntity;
use Illuminate\Support\Facades\Log;

class WechatOperationProxy
{
    /**
     * 下单
     * @param string $openId
     * @param string $tradeNo
     * @param int $totalFee
     * @return WechatPayResultMeta
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function pay(string $openId, string $tradeNo, int $totalFee)
    {
        $payment = WechatFactory::payment();
        $result = $payment->order->unify([
            'openid' => $openId,
            'out_trade_no' => $tradeNo,
            'total_fee' => $totalFee,
            'body' => '订单：' . $tradeNo,
            'trade_type' => 'JSAPI',
        ]);
        // 生成订单信息: {"return_code":"SUCCESS","return_msg":"OK","appid":"wxe320f577ae54b87f","mch_id":"1532490851","nonce_str":"qXrgYme9GgwP8Cmv","sign":"EBFFBA971CC482F01780A91B86B73947","result_code":"SUCCESS","prepay_id":"wx19152428659469a617667625ba9fdc0000","trade_type":"JSAPI"}
        Log::info('生成订单信息:', $result);

        return new WechatPayResultMeta($result);
    }

    /**
     * 退款
     * @param PaymentEntity $paymentEntity
     * @return WechatRefundResultMeta
     */
    public static function refund(PaymentEntity $paymentEntity)
    {
        $refundInfo = new WechatRefundMeta();
        $refundInfo->setOutTradeNo($paymentEntity->getTradeNo());
        $refundInfo->setOutRefundNo($paymentEntity->getRefundTradeNo());  // 连接生活的 refund_no 放入微信的 out_refund_no
        $refundInfo->setTotalFee($paymentEntity->getAmount());
        $refundInfo->setRefundFee($paymentEntity->getAmount());

        $wechatRet = [];

        Log::info('微信接口返回的退款数据', [$wechatRet]);
        return new WechatRefundResultMeta($wechatRet);
    }
}
